#include "utils.h"
#include <gtk/gtk.h>
#include <pango/pangocairo.h>
#include <fontconfig/fontconfig.h>

void utils_widget_set_css_classes(GtkWidget *widget, const char *classes)
{
    gchar **str_array = g_strsplit(classes, " ", -1);

    for (gchar **str = str_array; *str != NULL; str++)
    {
        gtk_widget_add_css_class(widget, *str);
    }

    g_strfreev(str_array);
}

static void on_widget_press(GtkGestureClick *gesture, gint n_press, gdouble x, gdouble y, gpointer user_data)
{
    GtkWindow *window = GTK_WINDOW(user_data);
    GdkSurface *surface = gtk_native_get_surface(gtk_widget_get_native(GTK_WIDGET(window)));
    GdkDevice *device = gtk_gesture_get_device((GTK_GESTURE(gesture)));
    gdk_toplevel_begin_move(GDK_TOPLEVEL(surface), device, n_press, x, y, time(NULL));
}

void utils_widget_set_can_drag_window(GtkWidget *widget)
{
    GtkEventController *controller = GTK_EVENT_CONTROLLER(gtk_gesture_click_new());
    gtk_widget_add_controller(widget, controller);
    gtk_event_controller_set_propagation_phase(controller, GTK_PHASE_TARGET);
    gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(controller), GDK_BUTTON_PRIMARY);
    GtkWidget *window = gtk_widget_get_ancestor(widget, GTK_TYPE_WINDOW);
    g_signal_connect(controller, "pressed", G_CALLBACK(on_widget_press), window);
}

void utils_load_css_from_resource(const char *resource_path)
{
    GdkDisplay *display = gdk_display_get_default();
    GtkCssProvider *provider = gtk_css_provider_new();
    gtk_css_provider_load_from_resource(provider, resource_path);
    gtk_style_context_add_provider_for_display(display, GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_USER);
}

void utils_load_font_from_resource(const char *resource_path)
{
    if (!FcInit())
    {
        g_warning("Failed to initialize Fontconfig\n");
        return;
    }
    FcConfig *config = FcConfigGetCurrent();
    if (FcConfigAppFontAddFile(config, (const FcChar8 *)resource_path) != FcTrue)
    {
        g_warning("Failed to load font file: %s\n", resource_path);
        return;
    }
    if (!FcConfigBuildFonts(config))
    {
        g_warning("Failed to build fonts in Fontconfig\n");
        return;
    }
    g_print("FontAwesome loaded successfully\n");
}